import { Canvas, Rect, Size, Vec3, director, size, v3, view } from "cc";
import { GlobalEnum } from "../Config/GlobalEnum";
import { GlobalTmpData } from "../Config/GlobalTmpData";
import EventManager from "../Managers/EventManager";
import { EventTypes } from "../Managers/EventTypes";
import { AudioSystem } from "../SystemAudio/AudioSystem";
import SDK, { VideoState } from "./SDK";
import { GlobalConfig } from "../Config/GlobalConfig";

const wx = window['wx'];

const WxAdCfg = {
    // 卓白-挪猪 wx86c10c5629b04fc3
    'wx86c10c5629b04fc3': {
        videoAd: 'adunit-90fb9736d72ffbda',
    },
    // 霆耀
    'wx5c96d9d84b8c40a1': {
        videoAd: 'adunit-37dd0b2d46802e4e',
    }
}

export class WXSDK extends SDK {

    api = wx;
    // _appid = 'wx86c10c5629b04fc3'; //卓白
    _appid = 'wx5c96d9d84b8c40a1'; //霆耀

    async initSdk(callback?: Function, target?: any) {
        this.api = wx;
        this.qingjs = wx['qingjs'];
        super.initSdk(callback, target);

        this.onUpdateExptParams();
        this._initVideo();
        this.onShare();

        console.log("WXSDK initSdk", this._appid);

        this.onGetUserCity();
    }

    onEvents() {
        super.onEvents();
        EventManager.on(EventTypes.SDKEvents.ShareImageMenu, this.onShareImageMenu, this);
    }

    //#region --- 更新实验参数
    onUpdateExptParams() {
        // 关卡
        // const expt_stage = wx.getExptInfoSync(['expt_stage']);
        // GlobalTmpData.ExptData.expt_stage = expt_stage.expt_stage;
        // // 体力
        // const expt_hp = wx.getExptInfoSync(['expt_hp']);
        // GlobalTmpData.ExptData.expt_energy = expt_hp.expt_hp;

        // 地图
        // const expt_map = wx.getExptInfoSync(['expt_map']);
        // GlobalTmpData.ExptData.expt_map = expt_map.expt_map;
        // // 排行
        // const expt_rank = wx.getExptInfoSync(['expt_rank']);
        // GlobalTmpData.ExptData.expt_rank = expt_rank.expt_rank;

        // console.log('更新实验参数：', GlobalTmpData.ExptData);
    }

    // 获取实验ID
    getExptId() {
        return '';
    }
    // 获取实验参数
    getExptParams() {
        let str = '';
        // str += 'expt_map_' + GlobalTmpData.ExptData.expt_map;
        // str += '&' + 'expt_rank_' + GlobalTmpData.ExptData.expt_rank;
        return str;
    }

    //#endregion

    //#endregion

    //#region --- 授权
    // 是否授权
    protected _isAuth = false;
    // 微信端授权按钮
    private userInfoButton;
    // 创建获取用户信息授权按钮
    private createUserInfoButton(rect, callback) {
        // 清除this.userInfoButton
        if (this.userInfoButton) {
            this.userInfoButton.destroy();
            this.userInfoButton = null;
        }
        // 重新创建
        // 通过 wx.getSetting 查询用户是否已授权头像昵称信息
        let screenSize = view.getVisibleSize();
        let systemInfo = wx.getSystemInfoSync();
        //
        let screenWidth = systemInfo.screenWidth;
        let screenHeight = systemInfo.screenHeight;
        // 否则，先通过 wx.createUserInfoButton 接口发起授权
        let leftPos = (rect.x - (rect.width / 2)) * screenWidth / screenSize.width;
        let topPos = ((screenSize.height - rect.y) - (rect.height / 2)) * screenHeight / screenSize.height;
        let trueWidth = rect.width * screenWidth / screenSize.width;
        let trueHeight = rect.height * screenHeight / screenSize.height;

        console.log("创建授权按钮")

        this.userInfoButton = wx.createUserInfoButton({
            type: 'text',
            text: '获取授权',
            style: {
                left: leftPos,
                top: topPos,
                width: trueWidth,
                height: trueHeight,
                lineHeight: 40,
                backgroundColor: '#00000000',
                color: '#00000000',     // 隐藏
                textAlign: 'center',
                fontSize: 16,
                borderRadius: 4
            }
        })

        // 点击
        this.userInfoButton.onTap((res) => {
            this.authUserInfo(callback);
            // 销毁
            if (this.userInfoButton) {
                this.userInfoButton.hide();
                this.userInfoButton.destroy();
                this.userInfoButton = null;
            }
        });
    }
    // 授权用户信息
    private authUserInfo(callback) {
        wx.getSetting({
            success(res) {
                if (res.authSetting['scope.userInfo']) {
                    // 已经授权，可以直接调用 getUserInfo 获取头像昵称
                    wx.getUserInfo({
                        success: function (res1) {
                            // console.log("22222222222222获取", res1.userInfo)
                            // var userInfo = res.userInfo
                            // var nickName = userInfo.nickName
                            // var avatarUrl = userInfo.avatarUrl
                            // var gender = userInfo.gender //性别 0：未知、1：男、2：女
                            // var province = userInfo.province
                            // var city = userInfo.city
                            // var country = userInfo.country
                            callback && callback(res1);
                        },
                        fail() {
                            console.log("11111111111111授权失败", res)
                            if (callback) {
                                callback(null);
                            }
                        }
                    })
                }
                else {
                    // 用户同意授权后回调，通过回调可获取用户头像昵称信息
                    wx.authorize({
                        scope: 'scope.userInfo',
                        success() {
                            //已经授权，可以直接调用 getUserInfo 获取头像昵称
                            wx.getUserInfo({
                                success: function (res1) {
                                    console.log("授权成功", res)
                                    if (callback) {
                                        callback(res1);
                                    }
                                },
                                fail() {
                                    console.log("1授权失败", res)
                                    if (callback) {
                                        callback(null);
                                    }
                                }
                            })
                        },
                        fail() {
                            console.log("拒绝授权", res)
                            if (callback) {
                                callback(null);
                            }
                        }
                    })
                }
            },
            fail(res) {
                console.log("0授权失败", res)
                if (callback) {
                    callback(null);
                }
                // userInfoButton.hide();
            }
        })
    }
    // 检测授权 / 已经授权之后调用
    protected onCheckUserInfoAuth(callback: Function) {
        console.log('# onCheckUserInfoAuth');
        wx.getSetting({
            success(res) {
                if (res.authSetting['scope.userInfo']) {
                    console.log('# 已经授权');
                    // 已经授权，可以直接调用 getUserInfo 获取头像昵称
                    wx.getUserInfo({
                        success: function (res1) {
                            callback && callback(res1);
                        },
                        fail: function () {
                            callback && callback(null);
                        }
                    })
                } else {
                    console.log('# 未授权');
                    callback && callback(null);
                }
            },
            fail(res) {
                console.log("获取授权失败", res)
                callback && callback(null);
            }
        })
    }
    // 创建授权点击按钮-> 授权 ->获取用户信息
    protected onGetUserInfo(rect: Rect, callback?) {
        this.createUserInfoButton(rect, callback);
    }
    protected onHideRankAuthBtn() {
        if (this.userInfoButton) {
            this.userInfoButton.hide();
            this.userInfoButton.destroy();
            this.userInfoButton = null;
        }
    }
    // 获取wx朋友圈按钮
    createGameClubButton(rect, callback) {
        // 通过 wx.getSetting 查询用户是否已授权头像昵称信息
        let screenSize = view.getVisibleSize();
        let systemInfo = wx.getSystemInfoSync();
        //当前sdk版本
        let screenWidth = systemInfo.screenWidth;
        let screenHeight = systemInfo.screenHeight;
        // 否则，先通过 wx.createUserInfoButton 接口发起授权
        let leftPos = (rect.x - (rect.width / 2)) * screenWidth / screenSize.width;
        let topPos = ((screenSize.height - rect.y) - (rect.height / 2)) * screenHeight / screenSize.height;
        let trueWidth = rect.width * screenWidth / screenSize.width;
        let trueHeight = rect.height * screenHeight / screenSize.height;
        console.log("systemInfo：", screenSize, screenWidth, screenHeight, leftPos, topPos)
        console.log("否则，先通过 wx.createUserInfoButton 接口发起授权", rect, leftPos, topPos)
        let userInfoButton = wx.createGameClubButton({
            type: 'text',
            text: '',
            icon: 'green',
            style: {
                left: leftPos,
                top: topPos,
                width: trueWidth,
                height: trueHeight,
                lineHeight: 40,
                backgroundColor: '#00000000',
                borderColor: '#00000000',
                borderWidth: 1,
                borderRadius: 4,
                textAlign: 'center',
                fontSize: 16,
                // lineHeight: 16,
            }
        })
        userInfoButton.onTap((res) => {
            if (callback) {
                callback();
            }
        });
        return userInfoButton;
    }
    // 获取用户所在城市
    onGetUserCity(callback?) {
        if (this._city) {
            callback && callback(true, this._city);
            return;
        }

        let self = this;
        wx.request({
            url: 'https://api.cxgame.net/app/sdk/v1/wx/ip-region',
            success(res) {
                let city = null
                if (res && res.data.code === 200) {
                    city = res.data.data.ip_region.city
                }
                if (city) {
                    self._city = city + '市';
                    console.log('用户所在城市:', self._city)
                    callback && callback(true, self._city);

                } else {
                    callback && callback(false, null)
                }
            },
            fail() {
                callback && callback(false, null)
            },
            responseType: "text"
        })
    }
    // 设置反馈按钮显示隐藏
    _feedbackBtn: any;
    protected onSetFeedbackBtn(rect, isShow?: boolean): void {
        if (isShow && rect) {
            if (!this._feedbackBtn) {
                let screenSize = view.getVisibleSize();
                let systemInfo = wx.getSystemInfoSync();
                //当前sdk版本
                let screenWidth = systemInfo.screenWidth;
                let screenHeight = systemInfo.screenHeight;
                // 否则，先通过  接口发起授权
                let leftPos = (rect.x - (rect.width / 2)) * screenWidth / screenSize.width;
                let topPos = ((screenSize.height - rect.y) - (rect.height / 2)) * screenHeight / screenSize.height;
                let trueWidth = rect.width * screenWidth / screenSize.width;
                let trueHeight = rect.height * screenHeight / screenSize.height;
                console.log("systemInfo：", screenSize, screenWidth, screenHeight, leftPos, topPos)

                this._feedbackBtn = wx.createFeedbackButton({
                    type: 'text',
                    text: '',
                    icon: 'green',
                    style: {
                        left: leftPos,
                        top: topPos,
                        width: trueWidth,
                        height: trueHeight,
                        lineHeight: 40,
                        backgroundColor: '#00000000',
                        borderColor: '#00000000',
                        borderWidth: 1,
                        borderRadius: 4,
                        textAlign: 'center',
                        fontSize: 16,
                        // lineHeight: 16,
                    }
                })
                this._feedbackBtn.show();
                this._feedbackBtn.onTap((res) => {
                    console.log('点击反馈按钮');
                });
            } else {
                this._feedbackBtn.show();
            }
        } else {
            this._feedbackBtn && this._feedbackBtn.hide();
        }
    }
    //#endregion

    //#region --- 排行榜

    // 设置好友排行
    onSetUserCloudStorage(key_v: string, value_v: number) {
        console.log('Message posted');
        wx.getOpenDataContext().postMessage({
            value: "setFriendData",
            strKey: key_v,
            score: value_v,
        });
    }
    // 获取好友排行
    onGetFriendCloudStorage(key_v: string, callback?: Function, userInfo?: any) {
        console.log('Message posted');
        wx.getOpenDataContext().postMessage({
            value: "getFriendData",
            strKey: key_v,
        });
    }

    //#endregion

    //#region --- 订阅
    // 订阅消息
    checkSubscribeMessage() {
    }

    //#endregion

    //#region --- 分享
    protected defaultTitle = '我不信你能过!';
    protected _url = 'https://cdn.cxgame.net/gamesupport/xiaoyouxi/zhuobai/';
    protected urlArr = {
        [GlobalEnum.SharePosition.HomePage]: [112],
        [GlobalEnum.SharePosition.GamePage]: [112],
        [GlobalEnum.SharePosition.WinPage]: [113],
        [GlobalEnum.SharePosition.LosePage]: [112],
    }

    protected curShareTitle = null;
    // 截图位置比例
    protected screenshotPos = v3(1, 1);
    // 截图大小比例 宽高比 5:4
    protected screenshotSize = size(1, 1);
    protected _canvas = null;

    // 分享截图路径 显示图片长宽比是 5:4
    private _getShareImageUrl() {
        const res = wx.getSystemInfoSync();
        const pixRate = res.pixelRatio; // 像素比
        const sw = res.windowWidth * pixRate;
        const sh = res.windowHeight * pixRate;

        if (!this._canvas) {
            // @ts-ignore
            this._canvas = wx.createCanvas();
            this._canvas.width = sw;
            this._canvas.height = sh;
        } else {
            let ctx = this._canvas.getContext('2d');
            ctx.clearRect(0, 0, this._canvas.width, this._canvas.height);
        }

        // 比例
        let xr = this.screenshotPos.x || 1;
        let yr = this.screenshotPos.y || 1;
        let wr = this.screenshotSize.width || 0.4;
        let hr = this.screenshotSize.height || 0.5;

        let w = wr * sw;
        let h = hr * sh;
        let x = xr * sw;
        let y = yr * sh;

        console.log('WX Share AreaSize: ', w, h, 'InfoSync size: ', sw, sh, 'pixRate: ', pixRate);
        try {
            // 同步方法
            let imageUrl = window['canvas'].toTempFilePathSync({
                x: x,
                y: y,
                width: w,
                height: h,
                destWidth: w,
                destHeight: h,
            })
            console.log('imageUrl', imageUrl);

            return imageUrl;
        } catch (error) {
            console.log('获取imageUrl失败!', error);
            return null;
        }
    }

    // 主动分享: useUrl: 是否使用远程图片
    protected share(d: { title: string, pos?: Vec3, useUrl?: boolean, urlType?: GlobalEnum.SharePosition, size?: Size, success?, fail?}): void {

        if (d && d.title) {
            this.curShareTitle = d.title;
        }
        // 大小比例参数
        if (d && d.size) {
            this.screenshotSize.set(d.size);
        }
        // 位置比例参数
        if (d && d.pos) {
            this.screenshotPos.set(d.pos);
        }

        console.log("# 主动分享:", this.curShareTitle, this.screenshotPos, this.screenshotSize);

        //随机 使用配置的路径-远程图片
        let imageUrl = null;

        if (d && !d.useUrl) {
            // 使用截屏
            imageUrl = this._getShareImageUrl();
        }

        if (!imageUrl) {
            //随机 使用配置的路径
            let urlType = d && d.urlType ? d.urlType : GlobalEnum.SharePosition.HomePage;
            let arr = this.urlArr[urlType];
            imageUrl = this._url + arr[Math.floor(Math.random() * arr.length)] + '.jpg';
        }
        // 默认视为成功
        this.onShareComplete();

        try {
            wx.shareAppMessage({
                title: this.curShareTitle || this.defaultTitle,
                imageUrl: imageUrl,
                success: () => {
                    console.log("分享成功");
                    if (d && d.success) {
                        d.success();
                    }
                },
                fail: () => {
                    console.log("分享失败2");
                    if (d && d.fail) {
                        d.fail();
                    }
                }
            })
        } catch (error) {
            console.log("分享失败3", error);
            if (d && d.fail) {
                d.fail();
            }
        }

    }
    // 被动分享-指定url
    onShare() {
        const self = this;
        this.curShareTitle = this.curShareTitle || this.defaultTitle;

        console.log("# 被动分享:", this.curShareTitle, this.screenshotPos, this.screenshotSize);

        //随机
        let arr = this.urlArr[GlobalEnum.SharePosition.HomePage];
        const imageUrl = this._url + arr[Math.floor(Math.random() * arr.length)] + '.jpg';

        try {
            wx.onShareAppMessage(() => {
                return {
                    title: self.curShareTitle,
                    imageUrl: imageUrl
                }
            })
        } catch (error) {
            console.log('onShareAppMessage 分享失败 ', error);
        }
    }
    // 分享图
    onShareImageMenu() {
        // 默认全屏
        this.screenshotPos.set(0, 0);
        this.screenshotSize.set(1, 1);

        if (this.isAndroid) {
            // 安卓无法使用此分享
            console.log(" onShareImageMenu 安卓无法使用此分享");
            return;
        }

        try {
            wx.showShareImageMenu({
                path: this._getShareImageUrl(),
                // 分享的图片消息是否要带小程序入口 (部分可用)
                needShowEntrance: true,
                success: () => {
                    console.log(" onShareImageMenu 分享成功");
                }
            })
        } catch (error) {
            this.showMessage('分享失败,稍后再试吧!');
            console.log('onShareImageMenu 分享失败 ', error);
        }

    }

    //#endregion

    //#region --- 广告

    /**
       * 插屏广告
       */
    protected showInterstitial(d?: { success?: Function, fail?: Function, close?: Function }) {
        console.log("showInterstitial");

    }
    /** 视频广告 */
    // loadState: 0 未加载 1 加载中 2 加载成功 3 加载失败 (VideoState)
    // 通用视频ID
    videoAdList = {
        [GlobalEnum.VideoIdx.LvPass]: { id: null, ui: '通关奖励', ad: null, state: VideoState.unLoad },
        [GlobalEnum.VideoIdx.Prop3]: { id: null, ui: '道具-匀速', ad: null, state: VideoState.unLoad },
        [GlobalEnum.VideoIdx.Prop2]: { id: null, ui: '道具-转向', ad: null, state: VideoState.unLoad },
        [GlobalEnum.VideoIdx.Prop1]: { id: null, ui: '道具-踢飞', ad: null, state: VideoState.unLoad },
        [GlobalEnum.VideoIdx.AddGold]: { id: null, ui: '金币不足', ad: null, state: VideoState.unLoad },
        [GlobalEnum.VideoIdx.Fail]: { id: null, ui: '复活', ad: null, state: VideoState.unLoad },
        [GlobalEnum.VideoIdx.UnlockAnimal]: { id: null, ui: '解锁动物', ad: null, state: VideoState.unLoad },
        [GlobalEnum.VideoIdx.HomeStartBtn]: { id: null, ui: '开始按钮', ad: null, state: VideoState.unLoad },
    };

    private _videoSuccessCb = null;
    private _videoFailCb = null;

    protected _initVideo() {
    }
    // 加载指定广告 并记录状态
    protected async _loadVideo(videoIdx: GlobalEnum.VideoIdx) {

        const rec = this.videoAdList[videoIdx];

        if (!rec.ad) {
            rec.state = VideoState.unLoad;

            if (!rec.id) {
                // 获取配置ID
                rec.id = WxAdCfg[this.appid].videoAd;
            }

            // multiton 多例模式
            rec.ad = wx.createRewardedVideoAd({ adUnitId: rec.id, multiton: false });
            rec.ad.offLoad();
            rec.ad.offError();
            rec.ad.offClose();

            // 加载成功
            rec.ad.onLoad(() => {
                rec.state = VideoState.success;
                console.log('激励视频 广告加载成功 ID: ' + rec.id);
            })
            // 加载失败
            rec.ad.onError(err => {
                console.log('激励视频 加载失败 ID:', rec.id, err);
                this.showMessage('暂时没有视频广告');
                rec.state = VideoState.unLoad;
            })

            // 用户点击了【关闭广告】按钮
            rec.ad.onClose(res => {
                // 小于 2.1.0 的基础库版本，res 是一个 undefined
                if (res && res.isEnded || res === undefined) {
                    // 正常播放结束，可以下发游戏奖励
                    if (this._videoSuccessCb) {
                        this._videoSuccessCb();
                    }
                    //播放完成LOG
                    this.onCompleteAd(rec.ui, 'video');
                    this.onVideoComplete();
                    console.log('激励视频 播放完成 ID: ' + rec.id);
                } else {
                    // 播放中途退出，不下发游戏奖励
                    if (this._videoFailCb) {
                        this._videoFailCb();
                    }
                    this.showMessage('播放完成才有游戏奖励哦');
                    console.log('激励视频 播放中途退出');
                }

                console.log('激励视频 广告关闭,准备预加载下一个');
                rec.state = VideoState.loading;

                // 恢复游戏+音乐
                EventManager.emit(EventTypes.GameEvents.GameResume);
                AudioSystem.resumeBGM();
            });
        }
        if (rec.state == VideoState.unLoad ||
            rec.state == VideoState.fail) {
            rec.state = VideoState.loading;
            await rec.ad.load();
            console.log('激励视频 广告开始加载 ID: ', rec.id);
        }
    }
    // 清除广告事件 + 状态
    protected clearVideoAd(idx) {
        if (this.videoAdList[idx]) {
            // 清除广告
            console.log('清除激励视频广告,ID:', this.videoAdList[idx].id);

            const ad = this.videoAdList[idx].ad;
            if (ad) {
                ad.offError();
                ad.offClose();
                ad.offLoad();
            }
            this.videoAdList[idx].state = VideoState.unLoad;
        }
    }
    /**
      * 拉起激励视频广告
      */
    protected async showRewardedVideo(cb: Function | { success: Function, fail: Function }, videoIdx = GlobalEnum.VideoIdx.LvPass) {

        // 测试 直接返回成功
        if (GlobalConfig.isCloseVideo) {
            // 记录回调参数
            if (typeof cb === 'object') {
                this._videoSuccessCb = cb.success;
                this._videoFailCb = cb.fail;
            } else {
                this._videoSuccessCb = cb;
            }
            setTimeout(() => {
                this._videoSuccessCb && this._videoSuccessCb();
                this.onVideoComplete();
                // 恢复游戏+音乐
                EventManager.emit(EventTypes.GameEvents.GameResume);
                AudioSystem.resumeBGM();
            }, 0);
            return;
        }


        const rec = this.videoAdList[videoIdx];
        if (!rec) {
            console.warn('没有视频广告配置 videoIdx : ' + videoIdx);
            return;
        }

        console.log('# 视频广告ID: ', rec.id, this.videoAdList[videoIdx].ui);

        // 显示触摸屏蔽
        this.showVideoTouchMask();

        // 判断状态
        let msg = null;
        if (rec.ad && rec.state == VideoState.loading) {
            msg = '激励视频 广告正在加载中,请稍后...';
            console.warn(msg);
            this.showMessage(msg);
            return;
        }

        // 重新加载
        if (!rec.ad || rec.state != VideoState.success) {
            this.showMessage('视频广告正在加载中,请稍后...');
            await this._loadVideo(videoIdx);
        }

        // 记录回调参数
        if (typeof cb === 'object') {
            this._videoSuccessCb = cb.success;
            this._videoFailCb = cb.fail;
        } else {
            this._videoSuccessCb = cb;
        }

        // 播放
        if (rec.ad) {
            //暂停游戏
            EventManager.emit(EventTypes.GameEvents.GamePause);
            AudioSystem.pauseBGM();
            console.log('激励视频 准备播放 ID: ', rec.id, rec.ad);

            // 播放
            rec.ad.show().then(() => {
                console.log('激励视频 广告显示成功');
                //播放LOG
                this.onShowAd(rec.ui, 'video');
            });
            // 点击LOG
            this.onClickAd(rec.ui, 'video');
        }
    }



    //#endregion

    //#region --- 硬件功能
    // 震动：heavy、medium、light
    // 短震动
    protected onShortVibration() {
        if (!wx || !GlobalTmpData.Setting.Audio.vibration) return;
        wx.vibrateShort({
            type: 'heavy',
        })
    }
    // 长震动
    protected onLongVibration() {
        if (!wx || !GlobalTmpData.Setting.Audio.vibration) return;
        wx.vibrateLong({
            type: 'heavy',
        })
    }
    //#endregion

    //#region --- 上报日志
    /**
     * wx.reportEvent('事件英文名', d:可json序列化对象)
     * @param key '事件英文名'
     * @param d 
     */
    onReportEvent(key: GlobalEnum.ReportName, d?): void {
        // 公共属性
        if (d) {
            d['new_user'] = this.isNewUser + '';
            // d['expt'] = this.getExptId();
            // d['exptvalue'] = this.getExptParams();
        }
        wx.reportEvent(key, d);
        console.log('上报日志：' + key, d);
    }
    // 分享转发
    onShareReport(ui: string) {
        let data = { opportunity: ui };
        // this.onReportEvent(GlobalEnum.ReportName.Share, data);
    }
    // 加载后进入游戏
    onLoadFinish(n: number): void {
        let data = { enter_count: n };
        this.onReportEvent(GlobalEnum.ReportName.LoadFinish, data);
    }
    // 引导步骤
    onGuideStep(step: number) {
        let data = {
            guide_step: step,
        };
        // this.onReportEvent(GlobalEnum.ReportName.Guide, data);
    }
    // 退出引导
    onSkipGuide(step: number) {
        let data = { guide_step: step };
        // this.onReportEvent(GlobalEnum.ReportName.Skip_guide, data);
    }

    // 完成新手引导
    onFinishGuide(time: number): void {
        let data = {
            stage_time: Math.floor(time)
        };
        // this.onReportEvent(GlobalEnum.ReportName.FinishGuide, data);
    }

    // 进入关卡
    onEnterStage() {
        let msg = this._getCurLvMsg();
        let data = {
            stage: msg,
            enter_count: GlobalTmpData.LvLogoData.enterCount,
        }
        // wx
        this.onReportEvent(GlobalEnum.ReportName.EnterStage, data);
        // cx
        this.qingjs && this.qingjs.instance.eventReporter.enterStage(data);
    }
    // 退出关卡
    onExitStage(state: GlobalEnum.ExitLvState) {

        // 微信上报
        let msg = this._getCurLvMsg();

        let data = {
            stage: msg,
            exit_info: this.exitStates[state],
            enter_count: GlobalTmpData.LvLogoData.enterCount,
            fail_count: GlobalTmpData.LvLogoData.failCount,
            //
            tip_count: GlobalTmpData.LvLogoData.tipCount,
            stage_time: Math.floor(GlobalTmpData.Game.gameTime),
            is_pass: (state == 0 ? 'true' : 'false'),
            //
            total_time: Math.floor((new Date().getTime() - GlobalTmpData.Game.gameLaunchTime) / 1000),
        };
        // wx
        this.onReportEvent(GlobalEnum.ReportName.ExitStage, data);
        // cx
        this.qingjs && this.qingjs.instance.eventReporter.exitStage(data);
    }
    // 显示广告按钮
    onShowAdButton(idx: GlobalEnum.VideoIdx, adType: string) {
        let data = {
            adType: 'video',
            opportunity: this.videoAdList[idx].ui,
        }
        // cx
        this.qingjs && this.qingjs.instance.eventReporter.showAdButton(data);
    }
    // 点击广告
    onClickAd(ui: string, adType: string) {
        let data = {
            adType: 'video',
            opportunity: ui,
        }
        // cx
        this.qingjs && this.qingjs.instance.eventReporter.clickAd(data);
    }
    // 展示广告
    onShowAd(ui: string, adType: string) {
        let is_stage = GlobalTmpData.Game.isGameOver ? 'false' : 'true';
        let data = {
            ad_type: 'video',
            opportunity: ui,
            is_stage: is_stage,
            stage: this._getCurLvMsg(),
        }
        // 微信上报
        this.onReportEvent(GlobalEnum.ReportName.ShowAd, data);

        let data2 = {
            adType: 'video',
            opportunity: ui,
            is_stage: is_stage,
            stage: this._getCurLvMsg(),
        }
        // cx
        this.qingjs && this.qingjs.instance.eventReporter.showAd(data2);
    }
    // 完整观看广告
    onCompleteAd(ui: string, adType: string) {
        let is_stage = GlobalTmpData.Game.isGameOver ? 'false' : 'true';
        let data = {
            ad_type: 'video',
            opportunity: ui,
            is_stage: is_stage,
            stage: this._getCurLvMsg(),
        }
        // 微信上报
        this.onReportEvent(GlobalEnum.ReportName.SuccessWatchAd, data);

        let data2 = {
            adType: 'video',
            opportunity: ui,
            is_stage: is_stage,
            stage: this._getCurLvMsg(),
        }
        // cx
        this.qingjs && this.qingjs.instance.eventReporter.completeAd(data2);
    }

    // 喂养动物
    onFeedAnimal(d?) {
        // 微信上报
        this.onReportEvent(GlobalEnum.ReportName.FeedAnimal, d);
        // cx
    }
    // 点击升级
    onLvupSpd(d?) {
        // 微信上报
        this.onReportEvent(GlobalEnum.ReportName.LvupSpd, d);
        // cx
    }

    //#endregion

}
